package com.ewzj.bigdata.mvp.ui.activity

import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.ewzj.bigdata.R
import com.ewzj.bigdata.app.config.AppKey
import com.ewzj.bigdata.app.extensions.dpToPx
import com.ewzj.bigdata.app.extensions.initcolor
import com.ewzj.bigdata.di.component.DaggerHourseListComponent
import com.ewzj.bigdata.di.module.HourseListModule
import com.ewzj.bigdata.mvp.contract.HourseListContract
import com.ewzj.bigdata.mvp.model.rspbean.CityBean
import com.ewzj.bigdata.mvp.model.rspbean.HomeBean
import com.ewzj.bigdata.mvp.model.rspbean.SubFilterBean
import com.ewzj.bigdata.mvp.presenter.HourseListPresenter
import com.ewzj.bigdata.mvp.ui.adapter.AreaAndPriceAdapter
import com.ewzj.bigdata.mvp.ui.adapter.FilterTypeAdapter
import com.ewzj.bigdata.mvp.ui.adapter.HomePageAdapter
import com.ewzj.bigdata.mvp.ui.adapter.MoretagAdapter
import com.jakewharton.rxbinding2.view.RxView
import com.jakewharton.rxbinding2.widget.RxTextView
import com.jakewharton.rxbinding2.widget.TextViewEditorActionEvent
import com.jess.arms.base.BaseActivity
import com.jess.arms.base.BaseApplication
import com.jess.arms.di.component.AppComponent
import com.jess.arms.utils.DataHelper
import com.jess.arms.utils.DeviceUtils
import com.jess.arms.utils.UiUtils
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.observables.GroupedObservable
import kotlinx.android.synthetic.main.activity_hourse_list.*
import kotlinx.android.synthetic.main.title_withsearch.*
import me.jessyan.rxerrorhandler.core.RxErrorHandler
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber
import java.util.*
import kotlin.properties.Delegates

class HourseListActivity : BaseActivity<HourseListPresenter>(), HourseListContract.View, AreaAndPriceAdapter.ItemChoiceListener {
    val hoursetype: Int by lazy { intent.getIntExtra(AppKey.EXTRA_DATA, 0) }
    lateinit var areview: View
    lateinit var typePopupview: View
    lateinit var priceview: View
    lateinit var morePopview: View
    lateinit var contentview: View
    private lateinit var typeFilterdatas: MutableList<SubFilterBean.DataEntity.ChildrenEntity>
    val headers = arrayOf("区域", "价格", "户型", "更多")
    lateinit var emptyview: View
    lateinit var popupViews: List<View>
    lateinit var swiperefresh: SwipeRefreshLayout
    lateinit var rvHourse: RecyclerView
    private var keywordprice = ""
    private var keywordarea = ""
    private var keywordtype = ""
    private var keywordmore = ""
    private var searchwords = ""
    private var areaId = "0"
    lateinit var rxErrorHandler: RxErrorHandler
//    val city: String by lazy { AppKey.city.city }
    var moreItemTagAdapter: MoretagAdapter by Delegates.notNull<MoretagAdapter>()

    override fun initAdapterEmptyView(adapter: HomePageAdapter) {
       adapter.emptyView=emptyview
    }
    override fun initRecylerView(adapter: HomePageAdapter) {
        rvHourse!!.layoutManager = LinearLayoutManager(this)
        rvHourse!!.adapter = adapter
        adapter.setOnLoadMoreListener(object : BaseQuickAdapter.RequestLoadMoreListener {
            override fun onLoadMoreRequested() {
                when (hoursetype) {
                    1 -> mPresenter.loadmoredata("1", getSeachwords(),areaId)
                    2 -> mPresenter.loadmoredata("8", getSeachwords(),areaId)
                    3 -> mPresenter.loadmoredata("9", getSeachwords(),areaId)
                    4 -> mPresenter.loadmoredata(null, getSeachwords(),areaId)
                    5 -> mPresenter.loadmoredata(null, getSeachwords(),areaId)
                }

            }

        }, rvHourse)
    }

    override fun initDropView(data: SubFilterBean) {

    }

    override fun initData(savedInstanceState: Bundle?) {
        rxErrorHandler = (this.application as BaseApplication).appComponent.rxErrorHandler()
        swiperefresh = contentview.findViewById(R.id.swipeRefreshLayout) as SwipeRefreshLayout
        rvHourse = contentview.findViewById(R.id.rv_content) as RecyclerView
        swiperefresh!!.initcolor()
        dropDownMenu.setDropDownMenu(Arrays.asList(*headers), popupViews, contentview)
        initlistener()
        when (hoursetype) {
            1 -> {
                mPresenter.subFilterlist("xinfang")
                mPresenter.loadHourses("1", getSeachwords(),areaId)
            }
            2 -> {
                mPresenter.subFilterlist("ershoufang")
                mPresenter.loadHourses("8", getSeachwords(),areaId)
            }
            3 -> {
                mPresenter.subFilterlist("zufang")
                mPresenter.loadHourses("9", getSeachwords(),areaId)
            }
            4 -> {
                mPresenter.subFilterlist("xiezilou")
                mPresenter.loadHourses(null, getSeachwords(),areaId)
            }
            5 -> {
                mPresenter.subFilterlist("shangpu")
                mPresenter.loadHourses(null, getSeachwords(),areaId)
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?): Int {
        areview = View.inflate(this, R.layout.popwindow_area, null)
        typePopupview = View.inflate(this, R.layout.popwindow_type, null)
        priceview = View.inflate(this, R.layout.popwindow_price, null)
        morePopview = View.inflate(this, R.layout.popwindow_more, null)
        contentview = View.inflate(this, R.layout.item_recylerview, null)
        emptyview = View.inflate(this, R.layout.error_view, null)
        popupViews = arrayListOf(areview, priceview, typePopupview, morePopview)
        return R.layout.activity_hourse_list
    }

    override fun setupActivityComponent(appComponent: AppComponent?) {
        DaggerHourseListComponent.builder().appComponent(appComponent)
                .hourseListModule(HourseListModule(this))
                .build()
                .inject(this)
    }

    override fun areaPopView(datas: SubFilterBean.DataEntity) {
        val recyclerView: RecyclerView = areview.findViewById(R.id.rv_area) as RecyclerView
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.addItemDecoration(HorizontalDividerItemDecoration.Builder(this)
                .colorResId(R.color.colorf7).size(2).margin(20.dpToPx(this), 20.dpToPx(this)).build())
        val areaAdapter = AreaAndPriceAdapter(datas.children)
        areaAdapter.itemChoiceListener = this
        areaAdapter.type = 1
        recyclerView.adapter = areaAdapter

    }

    override fun pricePopView(datas: SubFilterBean.DataEntity) {
        val recyclerView = priceview.findViewById(R.id.rv_price) as RecyclerView
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.addItemDecoration(HorizontalDividerItemDecoration.Builder(this)
                .colorResId(R.color.colorf7).size(2).margin(20.dpToPx(this), 20.dpToPx(this)).build())
        val priceAdapter = AreaAndPriceAdapter(datas.children)
        priceAdapter.setItemChoiceListener(this)
        priceAdapter.setType(2)
        val etlowprice: EditText = priceview.findViewById(R.id.price_low) as EditText
        val ethighprice = priceview.findViewById(R.id.price_high) as EditText
        if (hoursetype == 2) {
            //   二手房以万为单位，其余的以元
            etlowprice.hint = resources.getString(R.string.oldlowhint)
            ethighprice.hint = resources.getString(R.string.oldhighhint)
        } else {
            etlowprice.hint = resources.getString(R.string.newlowhint)
            ethighprice.hint = resources.getString(R.string.newhighhint)
        }
        val tvconfirm = priceview.findViewById(R.id.tv_confirm) as TextView
        tvconfirm.setOnClickListener(View.OnClickListener {
            if (TextUtils.isEmpty(etlowprice.text)) {
                UiUtils.SnackbarText("最低价格不能为空")
                return@OnClickListener
            }
            if (TextUtils.isEmpty(ethighprice.text)) {
                UiUtils.SnackbarText("最高价格不能为空")
                return@OnClickListener
            }
            priceFiter(etlowprice.text.toString(), ethighprice.text.toString())
        })
        recyclerView.adapter = priceAdapter
    }

    override fun typePopView(datas: SubFilterBean.DataEntity) {
        typeFilterdatas = datas.children
        val recyclerView = typePopupview.findViewById(R.id.rv_type) as RecyclerView
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.addItemDecoration(HorizontalDividerItemDecoration.Builder(this)
                .colorResId(R.color.colorf7).size(2).margin(20.dpToPx(this), 20.dpToPx(this)).build())
        val filterTypeAdapter = FilterTypeAdapter(datas.children)
        recyclerView.adapter = filterTypeAdapter
        typePopupview.findViewById(R.id.tv_confirm).setOnClickListener {
            typeFilter()
        }
    }

    override fun morePopView(datas: List<SubFilterBean.DataEntity>) {
        val recyclerView = morePopview.findViewById(R.id.rv_content) as RecyclerView
        recyclerView.layoutManager = LinearLayoutManager(this)
        moreItemTagAdapter = MoretagAdapter(datas)
        recyclerView.adapter = moreItemTagAdapter
        morePopview.findViewById(R.id.tv_clear).setOnClickListener {
            clearChoice(datas)
            keywordmore = ""
            dropDownMenu.setTabText("更多", false)
            loadHoursedata()
        }
        morePopview.findViewById(R.id.tv_confirm).setOnClickListener {
            moreFilter()
        }

    }

    override fun showLoading() {
        swiperefresh!!.isRefreshing = true
    }

    override fun launchActivity(intent: Intent?) {

    }

    override fun hideLoading() {
        swiperefresh!!.isRefreshing = false
    }

    override fun killMyself() {

    }

    override fun showMessage(message: String?) {

    }

    private fun priceFiter(low: String, high: String) {
        //1新房 2新闻 3装修图库 4数据 5评论 6视频 7装修公司 8二手房 9租房 10原创新闻
        when (hoursetype) {
            1 -> keywordprice = low + "-" + high + "元/㎡"
            2 -> keywordprice = low + "-" + high + "万"
            3 -> keywordprice = low + "-" + high + "元"
            else -> keywordprice = low + "-" + high + "元/㎡/月"
        }
        dropDownMenu.setTabText(keywordprice, null)
        DeviceUtils.hideSoftKeyboard(this, dropDownMenu)
        loadHoursedata()
    }

    fun clearChoice(subFilterBeens: List<SubFilterBean.DataEntity>) {
        for (dataEntity in subFilterBeens) {
            if (dataEntity.children != null) {
                for (childrenEntity in dataEntity.children) {
                    childrenEntity.setIsseld(false)
                }
            }
        }
        moreItemTagAdapter.notifyDataSetChanged()
    }

    private fun getSeachwords(): String {
        var cityjson=DataHelper.getStringSF(this,AppKey.LOCATION_CITY)
        var gson=(applicationContext as BaseApplication).appComponent.gson()
        var citybean=gson.fromJson(cityjson, CityBean.ListEntity::class.java)
        var city="成都"
        if (citybean!=null){
            city=citybean.city
        }
        var keyword = city ?: "成都"
        when (hoursetype) {
            4 -> keyword = "写字楼 " + keyword
            5 -> keyword = "商铺 " + keyword
        }
        if (!TextUtils.isEmpty(searchwords)) {
            keyword = keyword + " " + searchwords
        }
        if (!TextUtils.isEmpty(keywordarea)) {
            keyword = keyword + " " + keywordarea
        }
        if (!TextUtils.isEmpty(keywordtype)) {
            keyword = keyword + " " + keywordtype
        }
        if (!TextUtils.isEmpty(keywordprice)) {
            keyword = keyword + " " + keywordprice
        }
        if (!TextUtils.isEmpty(keywordmore)) {
            keyword = keyword + " " + keywordmore
        }
        return keyword
    }

    override fun makeChoice(childrenEntity: SubFilterBean.DataEntity.ChildrenEntity, type: Int) {
        if (type == 1) {
            if (childrenEntity.getName().equals("不限")) {
                keywordarea = ""
                areaId = "0"
            } else {
                areaId = childrenEntity.id
                keywordarea = childrenEntity.getName()
            }
        } else {
            if (childrenEntity.getName().equals("不限")) {
                keywordprice = ""
            } else {
                keywordprice = childrenEntity.getName()
            }
        }
        dropDownMenu.setTabText(childrenEntity.getName(), null)
        loadHoursedata()
    }

    fun loadHoursedata() {
        when (hoursetype) {
            1 -> {
                mPresenter.loadHourses("1", getSeachwords(),areaId)
            }
            2 -> {
                mPresenter.loadHourses("8", getSeachwords(),areaId)
            }
            3 -> {
                mPresenter.loadHourses("9", getSeachwords(),areaId)
            }
            4 -> {
                mPresenter.loadHourses(null, getSeachwords(),areaId)
            }
            5 -> {
                mPresenter.loadHourses(null, getSeachwords(),areaId)
            }
        }
    }

    fun moreFilter() {
        if (moreItemTagAdapter.selecteditems != null && moreItemTagAdapter.selecteditems.size > 0) {
            dropDownMenu.setTabText("更多", true)

            keywordmore = ""
            for (i in 0..moreItemTagAdapter.selecteditems.size - 1) {
                if (i != moreItemTagAdapter.selecteditems.size - 1) {
                    keywordmore = keywordmore + moreItemTagAdapter.selecteditems[i].name + " "
                } else {
                    keywordmore = keywordmore + moreItemTagAdapter.selecteditems[i].name
                }
            }
        } else {
            dropDownMenu.setTabText("更多", null)
            dropDownMenu.closeMenu()
        }
        loadHoursedata()
    }

    private fun typeFilter() {
        keywordtype = ""
        Observable.fromIterable(typeFilterdatas).
                groupBy { t -> t.isseld() }
                .filter { t -> t.key }
                .subscribe(object : ErrorHandleSubscriber<GroupedObservable<Boolean?, SubFilterBean.DataEntity.ChildrenEntity>>(rxErrorHandler) {
                    override fun onNext(booleanChildrenEntityGroupedObservable: GroupedObservable<Boolean?, SubFilterBean.DataEntity.ChildrenEntity>) {
                       booleanChildrenEntityGroupedObservable.toList().subscribe(Consumer { t ->run{
                           if (t.size > 1) {
                               for (i in t.indices) {
                                   if (t[i].name.equals("不限")) {
                                       keywordtype = ""
                                       break
                                   }
                                   if (i != t.size - 1) {
                                       keywordtype = keywordtype + t[i].name + " "
                                   } else {
                                       keywordtype = keywordtype + t[i].name
                                   }
                               }
                               if (TextUtils.isEmpty(keywordtype)) {
                                   dropDownMenu.setTabText("不限", null)
                               } else {
                                   dropDownMenu.setTabText("多选", null)
                               }
                           } else {
                               if (t[0].name.equals("不限")) {
                                   keywordtype = ""
                               } else {
                                   keywordtype = keywordtype + t[0].name
                               }

                               dropDownMenu.setTabText(t[0].name, null)
                           }
                           loadHoursedata()
                       }  })
                    }
                })
    }

    fun initlistener(){
        RxView.clicks(iv_back).subscribe(Consumer { finish() })
        RxView.clicks(iv_locate).subscribe(Consumer {
            var intent = Intent(this, MapActivity::class.java)
            intent.putExtra(AppKey.EXTRA_ID,hoursetype)
            when(hoursetype){
                1,2,3->{
                    startActivity(intent)
                }
                4,5->{
                    intent.putParcelableArrayListExtra(AppKey.EXTRA_DATA,mPresenter.adapter.data as ArrayList<HomeBean>)
                    startActivity(intent)
                }
            }
            })
        swiperefresh.setOnRefreshListener { loadHoursedata() }
        RxTextView.editorActionEvents(tv_search).observeOn(AndroidSchedulers.mainThread()).subscribe({ t: TextViewEditorActionEvent? -> run{
                if (t!!.actionId()==EditorInfo.IME_ACTION_SEARCH){
                    if (TextUtils.isEmpty(tv_search.getText())) {
                        UiUtils.SnackbarText("搜索内容不能为空")
                    } else {
                        DeviceUtils.hideSoftKeyboard(this@HourseListActivity,tv_search)
                        searchwords=tv_search.text.toString()
                        loadHoursedata()
                    }
                }

        } })
        RxTextView.afterTextChangeEvents(tv_search).observeOn(AndroidSchedulers.mainThread()).subscribe({
            run{
                if (tv_search.text.toString().isNullOrBlank()){
                        searchwords = ""
                        loadHoursedata()
                }
            }

        })
    }
}
